package com.cytech.cloudclinic.utils;

import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

public class OKHttpBodyParseHelper {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    /**
     * 获取请求体的字符串
     *
     * @param request
     * @return
     */
    public static String getReqBodyString(Request request) {
        String reqBody = "";
        try {
            Request copy = request.newBuilder().build();
            RequestBody body = copy.body();
            if (body == null) return reqBody;
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            Charset charset = OKHttpBodyParseHelper.getCharset(body.contentType());
            reqBody = buffer.readString(charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reqBody;
    }

    public static Charset getCharset(MediaType contentType) {
        Charset charset = contentType != null ? contentType.charset(UTF8) : UTF8;
        if (charset == null) charset = UTF8;
        return charset;
    }

    public static boolean isPlaintext(MediaType mediaType) {
        if (mediaType == null) return false;
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        String subtype = mediaType.subtype();
        if (subtype != null) {
            subtype = subtype.toLowerCase();
            if (subtype.contains("x-www-form-urlencoded") || subtype.contains("json") || subtype.contains("xml") || subtype.contains("html")) //
                return true;
        }
        return false;
    }
}
